package com.fary.chapter02_safe_thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition用法
 */
public class SafeThread09 {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        SafeThread09 safeThread09 = new SafeThread09();
        safeThread09.print();
        Thread.sleep(3000);
        safeThread09.signal();
    }

    public void print() {
        new Thread(() -> {
            try {
                // 释放锁 同时当前线程阻塞
                lock.lock();
                System.out.println(Thread.currentThread().getName() + ",1");
                condition.await();
                System.out.println(Thread.currentThread().getName() + ",2");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }

    public void signal() {
        try {
            lock.lock();
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
